﻿using System;
//using System.Web.Security;

using System.DirectoryServices;
using System.Text;


namespace LdapAuthentication
{
    public class LdapHelper
    {
        //private string _path = "LDAP://qu.edu.qa/DC=qu,DC=edu,DC=qa";
        //private string _filterAttribute;
        //private string domain = "qu.edu.qa";
        public LdapHelper()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        public static string GetLoginName(string username, string pwd, string displayName, string userID) //, string firstName, string lastName)
        {
            DirectoryEntry entry = new DirectoryEntry("LDAP://ldap.qu.edu.qa:389/ou=People,o=qu.edu.qa,o=cp", "uid=" + username + ",ou=People,o=qu.edu.qa,o=cp", pwd, AuthenticationTypes.None);
            try
            {
                SearchResult result = null;
                DirectorySearcher search = new DirectorySearcher(entry); 
                search.Filter = "(uid=" + userID + ")";
                search.SearchScope = SearchScope.Subtree;

                try
                {
                       result = search.FindOne();
                }
                catch
                { }

                if (result != null)
                    return userID; //UserID (e.g., StudentID) is the same the LoginName


                search.Filter = "(displayname=" + displayName + ")";
                search.SearchScope = SearchScope.Subtree;
                result = search.FindOne();

                string loginName = string.Empty;

                //StringBuilder sb = new StringBuilder();

                foreach (var name in result.Properties.PropertyNames)
                {
                    if (name.ToString() == "uid")
                    {
                        loginName = result.Properties[name.ToString()][0].ToString();
                        break;
                    }
                    //sb.Append(string.Format("{0} - {1} \n", name, result.Properties[name.ToString()][0].ToString()));
                }

                //Console.WriteLine(sb.ToString());

                return loginName;
            }
            catch
            {
                return string.Empty;
                //throw new Exception("Authentication failed: " + ex.Message);
            }
        }

        public static bool IsAuthenticated(string username, string pwd)
        {
            DirectoryEntry entry = new DirectoryEntry("LDAP://ldap.qu.edu.qa:389/ou=People,o=qu.edu.qa,o=cp", "uid=" + username + ",ou=People,o=qu.edu.qa,o=cp", pwd, AuthenticationTypes.None);
            try
            {
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(uid=" + username + ")";
                search.SearchScope = SearchScope.Subtree;
                SearchResult result = search.FindOne();

                if (null == result)
                    return false;
                else
                    return true;
            }
            catch (Exception ex)
            {
                return false;
                //throw new Exception("Authentication failed: " + ex.Message);
            }
        }

        public static int get_user_id(string username, string pwd)
        {
            int id = 0;
            DirectoryEntry entry = new DirectoryEntry("LDAP://ldap.qu.edu.qa:389/ou=People,o=qu.edu.qa,o=cp", "uid=" + username + ",ou=People,o=qu.edu.qa,o=cp", pwd, AuthenticationTypes.None);
            try
            {
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(uid=" + username + ")";
                search.SearchScope = SearchScope.Subtree;
                search.PropertiesToLoad.Add("pdsExternalSystemID");
                SearchResult result = search.FindOne();
                string user_id = "";
                user_id = result.Properties["pdsExternalSystemID"][0].ToString();

                id = Int32.Parse(user_id.Substring(0, 5));

                if (null == result)
                {
                    return 0;
                }
            }
            catch (DirectoryServicesCOMException ex)
            {
                throw new Exception("Error authenticating user. " + ex.Message);
            }
            return id;
        }


        //public static void GetInfoForAllUsers()
        //{
        //    //Console.Write("Enter property: ");  
        //    string property = "mail";

        //    try
        //    {
        //        DirectoryEntry myLdapConnection = createDirectoryEntry();

        //        DirectorySearcher search = new DirectorySearcher(myLdapConnection);
        //        search.PropertiesToLoad.Add("cn");
        //        search.PropertiesToLoad.Add(property);

        //        SearchResultCollection allUsers = search.FindAll();

        //        foreach (SearchResult result in allUsers)
        //        {
        //            if (result.Properties["cn"].Count > 0 && result.Properties[property].Count > 0)
        //            {
        //                Console.WriteLine(String.Format("{0,-20} : {1}",
        //                              result.Properties["cn"][0].ToString(),
        //                              result.Properties[property][0].ToString()));
        //            }
        //        }
        //    }

        //    catch (Exception e)
        //    {
        //        Console.WriteLine("Exception caught:\n\n" + e.ToString());
        //    }
        //}

        //static DirectoryEntry createDirectoryEntry()
        //{
        //    string username = "erradi";
        //    string pwd = "????";
        //    DirectoryEntry ldapConnection = new DirectoryEntry("LDAP://ldap.qu.edu.qa:389/ou=People,o=qu.edu.qa,o=cp", "uid=" + username + ",ou=People,o=qu.edu.qa,o=cp", pwd, AuthenticationTypes.None);
        //    // create and return new LDAP connection with desired settings  
        //    //DirectoryEntry ldapConnection = new DirectoryEntry("ldap.qu.edu.qa:389");
        //    //ldapConnection.Path = "ou=People,o=qu.edu.qa,o=cp";
        //    //ldapConnection.AuthenticationType = AuthenticationTypes.Anonymous;
        //    return ldapConnection;
        //}



        //Faculty
        //-------
        //sn - Erradi
        //givenname - Abdelkarim
        //displayname - Abdelkarim Erradi
        //title - Assistant Professor of Computer Science 
        //uid - erradi 
        //pdsrole - faculty 
        //departmentnumber - 183 
        //pdsgender - M 
        //mail - erradi@qu.edu.qa 
        //telephonenumber - 4254 
        //ou - Engineering 
        //pdsexternalsystemid - 12504::sct
        //(the above is JobNo)


        //Student
        //-------
        //displayname - Oumar Mahamdut Seid 
        //pdsemaildefaultaddress - 200407161@qu.edu.qa 
        //pdsemaildefaultaccount - Qatar University Mail 
        //objectclass - top 
        //pdsloginalias - 200407161 
        //pdsemailaccount - /v8AUQBhAHQAYQByACAAVQBuAGkAdgBlAHIAcwBpAHQAeQAgAE0AYQBpAGw=,3,mymail.qu.edu.qa,200407161@qu.edu.qa,200407161,0,0 
        //pdsloginid - 200407161 
        //givenname - Oumar 
        //sn - Seid 
        //uid - 200407161 
        //adspath - LDAP://ldap.qu.edu.qa:389/uid=200407161,ou=People,o=qu.edu.qa,o=cp 
        //mail - 200407161@qu.edu.qa 

    }
}

